const R = require('koa-router');
let router = new R();
const fs = require('fs')
const path=require('path')
const { photoCode }= require('../tool/tool.js')


// 自定义异常类
class MyError extends Error {
    constructor(message, errno) {
        super(message)
        this.name = "MyError"
        this.errno = errno
    }
}

router.post('/files', async function (ctx) {
    // 设置上传目录
    let d = new Date()
    let fileDir = `./uploads/${d.getFullYear()}/${d.getMonth()}/${d.getDate()}/`;
    // 创建目录
    await fs.promises.mkdir(fileDir, { recursive: true })
    // // 写入文件
    // 读取文件流
    let files =[ctx.request.files.photo] 
    let photoUrl = []
    let photocode = await photoCode()
    for (let file of files) {
        const reader = fs.createReadStream(file.path);
        // 写入流
        const upStream = fs.createWriteStream(fileDir +photocode+ file.name); 
        photoUrl.push((fileDir + photocode + file.name).slice(10)) 
        // 可读流通过管道写入可写流
        reader.pipe(upStream);
    }
    // console.log(photoUrl);
    ctx.body={photoUrl}
})


module.exports = router